/// doc: https://webpack.js.org/configuration/dev-server/#devserverbefore
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

function fetchFile(_path = __dirname, reg = /[\S\s]/) { // XXX: 模拟Webpack.require.context递归查找模块文件
    return fs.readdirSync(_path, { withFileTypes: true }).reduce((manifest, file) => {
        const { name } = file;
        if (__filename === path.join(_path, name)) return manifest; // 本文件

        if (file.isDirectory()) { // 目录递归
            return [
                ...manifest,
                ...fetchFile(path.resolve(_path, file.name), reg)
            ];
        }

        return reg.test(name) ? manifest.concat(path.resolve(_path, name)) : manifest; // 符合规则的文件
    }, []);
}

module.exports = function mockModules(app, server, compiler) {
    const modules = fetchFile(__dirname, /\.js$/);
    app.use(bodyParser.urlencoded({ extended: false })); // 解析: application/x-www-form-urlencoded
    app.use(bodyParser.json()); // 解析: parse application/json

    modules.forEach((module) => {
        // eslint-disable-next-line import/no-dynamic-require
        const mockInstance = require(module);
        if (typeof mockInstance !== 'function') {
            throw new Error(`
            ${module} 必须导出一个函数[mockInstance(app: express.Application, server, compiler) => void]
            `);
        }

        mockInstance.call(Object.create(null), app, server, compiler);
    });
};
